package jdktcp.client;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class JDKTcpClient4Baidu {

    static int timeout = 1000 * 10;

    public static void main(String[] args) throws Exception {
        new JDKTcpClient4Baidu().sendHttp(null);
    }

    public void sendHttp(String msg) {
        Socket client = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            StringBuilder sb = new StringBuilder();
            //sb.append("POST /mock HTTP/1.1\r\n");
            //sb.append("Host: localhost:8091\r\n");
            //sb.append("Connection: Close\r\n\r\n");
            //sb.append(msg);

            String messageData = sb.toString();

            messageData = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: Close\r\n\r\n";

            System.out.println("send data:" + messageData);

            client = new Socket();
            SocketAddress endpoint = new InetSocketAddress("www.baidu.com", 80);
            client.connect(endpoint, timeout);

            out = client.getOutputStream();
            out.write(messageData.getBytes());
            out.flush();
            System.out.println("-----------------------------------");

            in = client.getInputStream();
            byte[] data = IOUtils.toByteArray(in);
            System.out.println("response data:\n" + new String(data));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (client != null) client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
